#！D:\MyWork\Program\python
# -*- coding: utf-8 -*-
import re
import pymysql
import traceback
if __name__ == '__main__':
    #5c63e62b1c039631b525079c
    conn = pymysql.Connect(host = 'localhost',
                           port = 3306,
                           user = 'root',
                           passwd = 'root',
                           db = 'boos',
                           charset='utf8mb4')
    cur = conn.cursor()
    p = re.compile('\|\|\|',re.S)
    p1= re.compile(':::',re.S)
    p2 = re.compile('\|\*\|',re.S)
    with open("C:\\Users\\diao\\Desktop\\target2.txt","r",encoding='utf-8') as books:
        for line in books:
            try:
                line=line.replace('\n', '')
                infolist=p2.split(line)
                book_id=infolist[8]
                f = open("C:\\Users\\diao\\Desktop\\details\\"+book_id+".txt","r",encoding='utf-8')
                data=f.read()
                if "|||" in data:
                    weblist = p.split(data)
                    for webindex in range(len(weblist)):
                        webdata=weblist[webindex]
                        textlist=p1.split(webdata)
                        catalog=textlist[0]
                        text=textlist[1]
                        into = "INSERT INTO books_con(`书名`,`简介`,`作者`,`国籍`,`创作时间`,`创作时期`,`书籍领域`,`版本语言`,`目录`,`内容`,book_id) VALUES (%s,%s, %s, %s,%s,%s, %s, %s,%s,%s,%s)"
                        values = (infolist[0],infolist[1],infolist[2],infolist[3],infolist[4],infolist[5],infolist[6],infolist[7],catalog,text,book_id)
                        cur.execute(into, values)
                        conn.commit()
                else:
                    textlist=p1.split(data)
                    catalog=textlist[0]
                    text=textlist[1]
                    into = "INSERT INTO books_con(`书名`,`简介`,`作者`,`国籍`,`创作时间`,`创作时期`,`书籍领域`,`版本语言`,`目录`,`内容`,book_id) VALUES (%s,%s, %s, %s,%s,%s, %s, %s,%s,%s,%s)"
                    values = (infolist[0],infolist[1],infolist[2],infolist[3],infolist[4],infolist[5],infolist[6],infolist[7],catalog,text,book_id)
                    cur.execute(into, values)
                    conn.commit()
                f.close()
            except Exception:
                traceback.print_exc()
                print("异常id: "+book_id)
                continue

    conn.close()
    books.close()